<template>
  <div>
    <div v-if="mode === 'DESIGN'">
      <div class="design">
        <el-icon><plus/></el-icon>
      </div>
      <p>{{ placeholder }} {{ sizeTip }}</p>
    </div>
    <div v-else-if="mode === 'PC' && !readonly">
      <el-upload :file-list="fileList" :action="uploadUrl" :limit="maxNumber" with-credentials :multiple="maxNumber > 1"
        :data="uploadParams" :on-success="uploadSuccess" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
        :on-exceed="overLimit" :on-error="uploadFail" list-type="picture-card" auto-upload :before-upload="beforeUpload">
        <template #default>
          <el-icon><Plus/></el-icon>
        </template>
        <template #tip>
          <div class="el-upload__tip">{{ placeholder }} {{ sizeTip }}</div>
        </template>
      </el-upload>
    </div>
    <div v-else-if="mode === 'MOBILE' && !readonly">
      <uploader v-model="fileList" :multiple="maxNumber > 1" :max-count="maxNumber > 0 ? maxNumber : 99"
        deletable :before-delete="handleRemove" :before-read="beforeUpload" :upload-text="$t('module.selectImg')" :after-read="afterRead"
        :max-size="maxSize > 0 ?  maxSize * 1024 * 1024 : undefined" @oversize="onOversize"/>
      <div style="color: #9b9595">{{ placeholder }} {{ sizeTip }}</div>
    </div>
    <div v-else class="img-preview">
      <div class="img-preview-pc">
        <el-image :alt="img.name" :src="$getRes(img.url)" v-for="(img,index) in _value" :key="index" :preview-src-list="pcImgList"/>
      </div>
    </div>
  </div>
</template>

<script>
import { Uploader, showSuccessToast, showFailToast } from 'vant'
import componentMinxins from '../ComponentMinxins'

export default {
  mixins: [componentMinxins],
  name: 'ImageUpload',
  components: { Uploader },
  props: {
    modelValue: {
      type: Array,
      default: () => {
        return []
      },
    },
    placeholder: {
      type: String,
      default: 'webAuto.PleaseSelectAnImage',
    },
    maxSize: {
      type: Number,
      default: 5,
    },
    maxNumber: {
      type: Number,
      default: 10,
    },
    enableZip: {
      type: Boolean,
      default: true,
    },
  },
  computed: {
    sizeTip() {
      return this.maxSize > 0 ? `| ${this.$t('webAuto.EachImage')}${this.maxSize}MB` : ''
    },
    pcImgList() {
      return this._value?.map((v) => this.$getRes(v.url))
    },
    fileList: {
      get() {
        return (this._value || []).map((f) => {
          return {
            name: f.name,
            url: this.$getRes(f.url),
            status: 'success',
          }
        })
      },
      set(val) {},
    },
  },
  data() {
    return {
      loading: false,
      disabled: false,
      uploadUrl: `${this.BASE_URL}/wflow/res`,
      uploadParams: { isImg: true },
      catchList: [],
      alows: ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'],
    }
  },
  methods: {
    beforeUpload(file) {
      this.catchList.length = 0
      if (Array.isArray(file)) {
        for (let i = 0; i < file.length; i++) {
          if (!this.validImage(file[i])) {
            return false
          }
        }
        return true
      } else {
        return this.validImage(file)
      }
    },
    validImage(img) {
      if (this.alows.indexOf(img.type) === -1) {
        this.$message.warning(this.$t('webAuto.unsupportedImage'))
      } else if (this.maxSize > 0 && img.size / 1024 / 1024 > this.maxSize) {
        this.$message.warning(`${this.$t('webAuto.singleImage')} ${this.maxSize}MB`)
      } else {
        this.loading = true
        return true
      }
      return false
    },
    removeFile(fileId) {
      this.$axios.delete(`${this.BASE_URL}/wflow/res/${fileId}`).then((rsp) => {
        this.$message.success(this.$t('webAuto.SuccessfullyRemoved'))
      })
    },
    uploadSuccess(response, file, fileList) {
      this.loading = false
      this.catchList.push(response)
      let ft = fileList.filter((f) => f.size !== undefined)
      if (this.catchList.length === ft.length) {
        this.$emit('update:modelValue', [...(this._value || []), ...this.catchList])
      }
      this.$message.success(response.name + this.$t('webAuto.UploadSuccessful') )
    },
    uploadFail(err) {
      this.loading = false
      this.$message.error(this.$t('webAuto.ImageUploadFailed') + err)
    },
    afterRead(file) {
      if (Array.isArray(file)) {
        file.forEach((fl) => {
          this.uploadFile(fl)
        })
      } else {
        this.uploadFile(file)
      }
    },
    uploadFile(file) {
      //上传文件
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('isImg', true)
      this.$axios
        .post(this.uploadUrl, formData, {
          'Content-type': 'multipart/form-data',
        })
        .then(
          (res) => {
            if (res.status === 200) {
              this._value.push(res.data)
              this.$emit('update:modelValue', this._value)
              showSuccessToast(this.$t('webAuto.UploadSuccessful'))
            }
          },
          (err) => {
            showFailToast(this.$t('webAuto.UploadFailed'))
            console.log(err)
          }
        )
    },
    overLimit() {
      if (this.mode === 'PC') {
        this.$message.warning(this.$t('webAuto.AtMost') + this.maxNumber + this.$t('webAuto.images'))
      } else {
        showFailToast(this.$t('webAuto.QuantityExceedsLimit'))
      }
    },
    onOversize(file) {
      showFailToast(this.$t('webAuto.imageTooLarge'))
    },
    handleRemove(file, fileList) {
      let i = this._value.findIndex((v) => v.name === file.name)
      if (i > -1) {
        //this.removeFile(this._value[i].id)
        this._value.splice(i, 1)
        this.$emit('update:modelValue', this._value)
      }
      console.log('删除文件', file)
    },
    handlePictureCardPreview(file) {
      console.log(file)
    },
    handleDownload(file) {
      console.log(file)
    },
  },
  emits: ['update:modelValue'],
}
</script>

<style lang="less" scoped>
.design {
  :deep(.el-icon) {
    padding: 10px;
    font-size: xx-large;
    background: white;
    border: 1px dashed #8c8c8c;
  }
}
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  line-height: 87px;
}
:deep(.el-upload-list__item) {
  width: 80px;
  height: 80px;
  transition: none;
  .el-upload-list__item-actions {
    & > span + span {
      margin: 1px;
    }
  }
}
:deep(.el-upload-list__item-preview) {
  display: none !important;
}
.img-preview {
  :deep(.img-preview-pc) {
    .el-image {
      width: 80px;
      height: 80px;
      margin: 5px;
    }
  }
}
</style>
